﻿using System;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public class ResItem : MonoBehaviour
{
    [SerializeField]
    protected RawImage m_image;
    [SerializeField]
    protected Text m_text;
    [SerializeField]
    protected Texture2D m_defaultTexture;
    protected Action<Route> onSelect { get; set; }
    protected Route m_route;
    protected Button m_button;
    protected AspectRatioFitter m_aspectRatio;
    public string guid { get { return m_route.guid; } }

    private void Awake()
    {
        m_button = GetComponent<Button>();
        m_button.onClick.AddListener(OnSelect);
        m_aspectRatio = m_image.GetComponent<AspectRatioFitter>();
    }

    private void OnSelect()
    {
        if (onSelect != null && m_route != null)
        {
            onSelect.Invoke(m_route);
        }
    }

    public void Init(Route route, Action<Route> onSelect)
    {
        m_route = route;
        this.onSelect = onSelect;
        m_image.texture = route.icon;
        m_text.text = route.name;

        if(m_image.texture == null)
        {
            m_image.texture = m_defaultTexture;
        }
        if (m_image.texture != null && m_aspectRatio)
        {
            var retio = (float)m_image.texture.width / m_image.texture.height;
            m_aspectRatio.aspectRatio = retio;
        }
    }

    public void SetStateOn(bool isOn)
    {
        if(isOn)
        {
            m_button.Select();
            if(onSelect != null)
            {
                onSelect.Invoke(m_route);
            }
        }
    }
}